import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:untitled1/routes.dart';

void main() {
  runApp(
    const ProviderScope(child: MyApp()),
  );
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      routerConfig: router,
    );
  }
}

class Student {
  int? id = 30;
  String? name = "";
}

class HomeStore extends StateNotifier<HomeStateData> {
  HomeStore()
      : super(HomeStateData(
            count: 1, name: 'cc', student: Student(), countList: []));

  initDate() async {
    print('刷新了方法');
    List<int> countList = [];
    countList.add(100);
    countList.add(101);
    countList.add(102);
    countList.add(103);
    var student1 = Student();
    student1.name = "张三";
    student1.id = 1;
    state = state.copyWith(countList: countList, student: student1);
  }

  removeOne() async {
    print('点击修改第一个值');
    // state.countList.remove(0);
    if (state.countList.isNotEmpty) {
      state.countList.removeLast();
    } else {
      await initDate();
    }
    state = state.copyWith(countList: state.countList);
  }

  updateStudent({Student? student}) {
    if (student != null) {
      state = state.copyWith(student: student);
    }
  }

  void incrementInt(int count) {
    state = state.copyWith(count: state.count + 1);
  }

  void updateName(String name) {
    state.student.name = (state.student.name! + name);
  }

  void updateId() {
    state.student.id = (state.student.id! + 1);
  }

  @override
  bool updateShouldNotify(HomeStateData old, HomeStateData current) {
    return !(old == current);
  }
}

class HomeRequest {}

class HomeStateData {
  HomeStateData(
      {required this.count,
      required this.name,
      required this.student,
      required this.countList});

  int count;
  String name;
  List<int> countList;
  Student student;

  HomeStateData copyWith(
      {int? count, String? name, Student? student, List<int>? countList}) {
    return HomeStateData(
        count: count ?? this.count,
        name: name ?? this.name,
        student: student ?? this.student,
        countList: countList ?? this.countList);
  }
}

final homeProviders = StateNotifierProvider<HomeStore, HomeStateData>((ref) {
  return HomeStore();
});

class HomePage extends ConsumerStatefulWidget {
  const HomePage({super.key});

  @override
  ConsumerState<ConsumerStatefulWidget> createState() => _HomePageState();
}

class _HomePageState extends ConsumerState<HomePage> {
  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback(
      (_) async {
        await ref.read(homeProviders.notifier).initDate();
      },
    );
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    var homeState = ref.watch(homeProviders);
    return Scaffold(
      appBar: AppBar(title: const Text('Counter example')),
      body: Column(
        children: [
          ...homeState.countList.map((e) {
            return Container(
              alignment: Alignment.center,
              width: 100,
              height: 20,
              margin: const EdgeInsets.all(20),
              color: Colors.white54,
              child: Text(
                "$e",
                style: const TextStyle(fontSize: 16),
              ),
            );
          }).toList(),
          Center(
            child: Text('${homeState.count}'),
          ),
          GestureDetector(
            onTap: () async {
              await ref.read(homeProviders.notifier).removeOne();
            },
            child: Container(
              width: 100,
              height: 30,
              color: Colors.red.shade100,
              child: const Text("点击修改数组第一个值"),
            ),
          ),
          Container(
            color: Colors.red.shade200,
            height: 100,
            width: 100,
            child: Column(
              children: [
                Text("${homeState.student.name}"),
                Text("${homeState.student.id}")
              ],
            ),
          ),
          Container(
            margin: const EdgeInsets.only(top: 10),
            color: Colors.red.shade200,
            height: 100,
            width: 100,
            child: TextButton(
              onPressed: () {
                var student3 = ref.read(homeProviders).student;
                student3.name = "555";
                ref
                    .read(homeProviders.notifier)
                    .updateStudent(student: student3);
              },
              child: const Text("点击修改学生"),
            ),
          ),
          Container(
            child: TextButton(
              onPressed: () {
                context.push("/login");
              },
              child: const Text("跳转到页面2"),
            ),
          )
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => ref.read(homeProviders.notifier).incrementInt(0),
        child: const Icon(Icons.add),
      ),
    );
  }
}
